package com.wang.project.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.project.annotation.AuthCheck;
import com.wang.project.common.BaseResponse;
import com.wang.project.common.DeleteRequest;
import com.wang.project.common.ErrorCode;
import com.wang.project.common.ResultUtils;
import com.wang.project.constant.UserConstant;
import com.wang.project.exception.BusinessException;
import com.wang.project.model.dto.user.*;
import com.wang.project.model.entity.User;
import com.wang.project.model.file.FileUserAvatarUrlVO;
import com.wang.project.model.vo.pay.RefreshKeyVo;
import com.wang.project.model.vo.UserVO;
import com.wang.project.service.UserKeyService;
import com.wang.project.service.UserService;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * 用户接口
 *
 * @author wangyuhang
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserKeyService userKeyService;


    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.userRegister(userRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info("user login :" + JSONUtil.toJsonStr(userLoginRequest));
        User user = userService.userLogin(userLoginRequest, request);
        log.info("user user :" + JSONUtil.toJsonStr(user));
        return ResultUtils.success(user);
    }

    /**
     * 邮箱登录
     *
     * @param userEmailLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/email/login")
    public BaseResponse<User> userEmailLogin(@RequestBody UserEmailLoginRequest userEmailLoginRequest, HttpServletRequest request) {
        if (userEmailLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(userService.userEmailLogin(userEmailLoginRequest, request));
    }

    /**
     * 邮箱验证码
     *
     * @param userEmailLoginRequest
     * @return
     */
    @PostMapping("/email/login/verificationCode")
    public BaseResponse<String> getEmailVerificationCode(@RequestBody UserEmailLoginRequest userEmailLoginRequest) {
        if (userEmailLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(userService.getEmailVerificationCode(userEmailLoginRequest));
    }

    /**
     * 用户退出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(userService.userLogout(request));
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<UserVO> getLoginUser(HttpServletRequest request) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        User user = userService.getLoginUser(request);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return ResultUtils.success(userVO);
    }


    /**
     * 创建用户
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        boolean result = userService.save(user);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        return ResultUtils.success(userService.deleteUser(deleteRequest,request));
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestParam(value = "file") MultipartFile file, UserUpdateRequest userUpdateRequest, HttpServletRequest request) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(userService.updateUser(file, userUpdateRequest, request));
    }

    /**
     * 根据 id 获取用户
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<UserVO> getUserById(int id, HttpServletRequest request) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        UserVO userVO = userService.getUserById(id, request);
        return ResultUtils.success(userVO);
    }

    /**
     * 获取用户列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<UserVO>> listUser(UserQueryRequest userQueryRequest, HttpServletRequest request) {
        List<UserVO> userVOList = userService.listUser(userQueryRequest, request);
        return ResultUtils.success(userVOList);
    }

    /**
     * 分页获取用户列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<UserVO>> listUserByPage(UserQueryRequest userQueryRequest, HttpServletRequest request) {
        Page<UserVO> userVOPage = userService.listUserByPage(userQueryRequest, request);
        return ResultUtils.success(userVOPage);
    }


    /**
     * 刷新用户ak sk
     * 当一个月到期后，之前的ak sk过期，提醒用户需要手动刷新ak sk
     *
     * @param request
     * @return
     */
    @GetMapping("/getSk")
    public BaseResponse<RefreshKeyVo> userGetSk(HttpServletRequest request) {
        RefreshKeyVo refreshKeyVo = userKeyService.refreshKey(request);
        return ResultUtils.success(refreshKeyVo);
    }
}
